package org.hepeng.fabric.gateway.event;

import org.springframework.util.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author he peng
 * @date 2022/3/30
 */
public class NamedThreadFactory implements ThreadFactory {

    private final String prefix;

    private final ThreadGroup group;

    private final AtomicInteger threadNumber = new AtomicInteger(1);

    private final boolean isDaemon;

    private final Thread.UncaughtExceptionHandler handler;


    public NamedThreadFactory(String prefix, boolean isDaemon) {
        this(prefix, null, isDaemon);
    }


    public NamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon) {
        this(prefix, threadGroup, isDaemon, null);
    }


    public NamedThreadFactory(String prefix, ThreadGroup threadGroup, boolean isDaemon, Thread.UncaughtExceptionHandler handler) {

        this.prefix = StringUtils.hasText(prefix) ? prefix : "";
        if (null == threadGroup) {
            threadGroup = Thread.currentThread().getThreadGroup();
        }
        this.group = threadGroup;
        this.isDaemon = isDaemon;
        this.handler = handler;
    }

    @Override
    public Thread newThread(Runnable r) {

        final Thread t = new Thread(this.group, r, String.format("%s-%s" ,  prefix, threadNumber.getAndIncrement()));

        if (!t.isDaemon()) {
            if (isDaemon) {
                t.setDaemon(true);
            }
        } else if (!isDaemon) {
            t.setDaemon(false);
        }
        if(null != this.handler) {
            t.setUncaughtExceptionHandler(handler);
        }
        if (Thread.NORM_PRIORITY != t.getPriority()) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
